#include "hal.h"
#include <raw_api.h>

#if (HAL_USE_SPI > 0) 


HAL_ERROR spi_init(SPI_DRIVER *spi) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(spi != 0);

	mutex_error = raw_mutex_get(&spi->spi_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
  	ret = spi_lld_init(spi);

	mutex_error = raw_mutex_put(&spi->spi_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
}


HAL_ERROR spi_start(SPI_DRIVER *spi, SPI_CONFIG *config) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT((spi != 0) && (config != 0));

	mutex_error = raw_mutex_get(&spi->spi_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	spi->config = config;
	ret = spi_lld_start(spi, config);
	
	mutex_error = raw_mutex_put(&spi->spi_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
}


HAL_ERROR spi_stop(SPI_DRIVER *spi) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(spi != 0);

	mutex_error = raw_mutex_get(&spi->spi_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = spi_lld_stop(spi);
	
	mutex_error = raw_mutex_put(&spi->spi_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
}


HAL_ERROR spi_transmit(SPI_DRIVER *spi, RAW_U8 *tx_buf, RAW_U32 tx_bytes, 
								 RAW_U8 *rx_buf, RAW_U32 rx_bytes, RAW_U32 timeout)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(spi != 0);

	mutex_error = raw_mutex_get(&spi->spi_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = spi_lld_transmit(spi, tx_buf, tx_bytes, rx_buf, rx_bytes, timeout);
	
	mutex_error = raw_mutex_put(&spi->spi_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;

}


HAL_ERROR spi_receive(SPI_DRIVER *spi, RAW_U8 *rx_buf, RAW_U32 rx_bytes, RAW_U32 timeout)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(spi != 0);
	
	mutex_error = raw_mutex_get(&spi->spi_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = spi_lld_receive(spi, rx_buf, rx_bytes, timeout);
	
	mutex_error = raw_mutex_put(&spi->spi_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;

}


HAL_ERROR spi_deinit(SPI_DRIVER *spi) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(spi != 0);

	mutex_error = raw_mutex_get(&spi->spi_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
  	ret = spi_lld_deinit(spi);

	mutex_error = raw_mutex_put(&spi->spi_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
	
}


#endif 


